package com.palfund.fragmentradiogroup;

import android.content.res.TypedArray;
import android.graphics.Color;
import android.graphics.PorterDuff;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.support.v7.app.AppCompatActivity;
import android.util.TypedValue;
import android.view.Gravity;
import android.widget.RadioButton;
import android.widget.RadioGroup;

import java.util.ArrayList;

public class MainActivity extends AppCompatActivity {
    private int curIndex = 0;
    private RadioGroup mRadioGroup;
    private ArrayList<BlankFragment> mList;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        // 初始化控件
        initView();
        // 初始化tabs
        initTabs();
    }

    private void initTabs() {
        // 获取tabs的title
        final String[] titles = getResources().getStringArray(R.array.arrTabTitles);
        // 获取无类型数组
        TypedArray typedArray = getResources().obtainTypedArray(R.array.arrIconDrawable);
        // 创建RadioButton中drawable的数组
        final Drawable[] drawables = new Drawable[titles.length];
        mList = new ArrayList<>();
        // 创建Fragment以及radioButton
        for (int i = 0; i < titles.length; i++) {
            BlankFragment fragment = BlankFragment.newInstance(i);
            mList.add(fragment);
            RadioButton radioButton = new RadioButton(this);
            // 设置文字
            radioButton.setText(titles[i]);
            // 设置文字颜色
            radioButton.setTextColor(Color.GRAY);
            // 设置字体大小
            radioButton.setTextSize(TypedValue.COMPLEX_UNIT_SP, 16);
            // 去除小圆点
            radioButton.setButtonDrawable(android.R.color.transparent);
            // 去除点击阴影
            radioButton.setBackgroundResource(android.R.color.transparent);
            // 获取屏幕的宽度
            int widthPixels = getResources().getDisplayMetrics().widthPixels;
            // 设置radioButton的宽度
            radioButton.setWidth(widthPixels / titles.length);
            // 设置radioButton文字居中
            radioButton.setGravity(Gravity.CENTER);
            drawables[i] = typedArray.getDrawable(i);
            // drawable.setBounds(0,0,drawable.getMinimumWidth(),drawable.getMinimumHeight());
            drawables[i].setBounds(0, 0, drawables[i].getMinimumWidth(), drawables[i]
                    .getMinimumHeight());
            // drawable.setColorFilter(Color.GREEN, PorterDuff.Mode.SRC_IN);
            // 为radioButton设置图片
            radioButton.setCompoundDrawables(null, drawables[i], null, null);
            // 为radioButton设置文字和图片间的间距
            radioButton.setCompoundDrawablePadding(5);
            mRadioGroup.addView(radioButton);
        }
        // 设置默认显示
        RadioButton radioButtonDefult = (RadioButton) mRadioGroup.getChildAt(0);
        radioButtonDefult.setChecked(true);
        radioButtonDefult.setTextColor(Color.BLUE);
        drawables[0].setColorFilter(Color.BLUE, PorterDuff.Mode.SRC_IN);
        FragmentManager fragmentManager = getSupportFragmentManager();
        BlankFragment fragment = mList.get(0);
        fragmentManager.beginTransaction().add(R.id.layout_container, fragment).commit();
        // 释放资源  清空回退栈
        //boolean poped = fragmentManager.popBackStackImmediate();
        //Log.i("MainActivity", "---initTabs()--->" + poped);
        mRadioGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup group, int checkedId) {
                for (int i = 0; i < titles.length; i++) {
                    // 判断选中的tab,并更改tabs状态
                    RadioButton radioButtonTarget = (RadioButton) mRadioGroup.getChildAt(i);
                    if (radioButtonTarget.getId() == checkedId) {
                        // 更改选中的tab的状态
                        radioButtonTarget.setTextColor(Color.BLUE);
                        drawables[i].setColorFilter(Color.BLUE, PorterDuff.Mode.SRC_IN);
                        // 更改未选中的tab的状态
                        RadioButton radioButtonCurrent = (RadioButton) mRadioGroup.getChildAt
                                (curIndex);
                        radioButtonCurrent.setTextColor(Color.GRAY);
                        drawables[curIndex].setColorFilter(Color.GRAY, PorterDuff.Mode.SRC_IN);
                        // 切换Fragment
                        switchFragment(i, mList);
                        // 替换Fragment
                        // replaceFragment(i, list);
                        return;
                    }
                }
            }
        });
    }

    private void replaceFragment(int targetIndex, ArrayList<BlankFragment> list) {
        //获取FragmentManager对象
        FragmentManager fragmentManager = getSupportFragmentManager();
        // 获取FragmentTransaction对象
        FragmentTransaction transaction = fragmentManager.beginTransaction();
        // 获取目标Fragment
        Fragment targetFragment = list.get(targetIndex);
        // 替换
        transaction.replace(R.id.layout_container, targetFragment);
        // 将Fragment添加到回退栈
        // 备注:调用replace()方法时,如果不调用addToBackStack()方法将当前Fragment加入到回退栈中当前Fragment将会被销毁
        // (再次显示此Fragment需要重新创建);加入到回退栈中当前Fragment只会销毁View(再次显示此Fragment只需重新创建View)
        // transaction.addToBackStack("");
        // transaction  commit后对Fragment的操作才生效,transaction只能提交一次
        transaction.commit();
        curIndex = targetIndex;
    }

    private void initView() {
        mRadioGroup = (RadioGroup) findViewById(R.id.radioGroup);
    }

    private void switchFragment(int targetIndex, ArrayList<BlankFragment> list) {
        //获取FragmentManager对象
        FragmentManager fragmentManager = getSupportFragmentManager();
        // 获取FragmentTransaction对象
        FragmentTransaction transaction = fragmentManager.beginTransaction();
        // 获取目标Fragment
        Fragment targetFragment = list.get(targetIndex);
        // 获取当前Fragment
        Fragment curFragment = list.get(curIndex);
        // 隐藏当前Fragment 调用hide()、show()不执行生命周期方法
        transaction.hide(curFragment);
        // 判断目标Fragment是否已经添加过,添加过就显示,否则就添加
        if (targetFragment.isAdded()) {
            transaction.show(targetFragment);
        } else {
            //添加Fragment,已经添加过就不能再添加了
            transaction.add(R.id.layout_container, targetFragment);
        }
        // transaction  commit后对Fragment的操作才生效
        transaction.commit();
        curIndex = targetIndex;
    }

    //退出前显示默认页
    @Override
    public void onBackPressed() {
        if (mList.get(0).isHidden()) {
            ((RadioButton) mRadioGroup.getChildAt(0)).setChecked(true);
            return;
        }
        super.onBackPressed();
    }

}
